package com.ctrip.ec.api.mobile.common;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import java.util.concurrent.ExecutionException;

/**
 * Created by cannon on 2018/3/26.
 */
public class MapperBuilder {

    private static LoadingCache<Long, JsonMapper> CACHE = CacheBuilder.newBuilder().maximumSize(1000).build(new CacheLoader<Long, JsonMapper>() {
        @Override
        public JsonMapper load(Long key) throws Exception {
            return buildMapper(key);
        }
    });
    static long default_features = 0L;
    private static final JsonMapper def = MapperBuilder.create().build();

    public static JsonMapper getDefaultMapper() {
        return def;
    }


    public MapperBuilder() {
    }

    public static MapperBuilder create() {
        return new MapperBuilder();
    }


    public JsonMapper build() {
        try {
            return CACHE.get(default_features);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }


    public static JsonMapper buildMapper(long features) {

        ObjectMapper om = new ObjectMapper();
        JsonMapper mapper = new JsonMapper(om);
        CACHE.put(features, mapper);

        return mapper;
    }

    private static void configure(ObjectMapper om, Object feature, boolean state) {
        if (feature instanceof SerializationFeature)
            om.configure((SerializationFeature) feature, state);
        else if (feature instanceof DeserializationFeature)
            om.configure((DeserializationFeature) feature, state);
        else if (feature instanceof JsonParser.Feature)
            om.configure((JsonParser.Feature) feature, state);
        else if (feature instanceof JsonGenerator.Feature)
            om.configure((JsonGenerator.Feature) feature, state);
        else if (feature instanceof MapperFeature)
            om.configure((MapperFeature) feature, state);
        else if (feature instanceof JsonInclude.Include) {
            if (state) {
                om.setSerializationInclusion((JsonInclude.Include) feature);
            }
        }
    }
}
